﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

using VoiceControlDesktopClient.Functions;
using Ini;
using System.Runtime.InteropServices;

namespace VoiceControlDesktopClient
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

        }
        Thread reThread = null;
        Socket sc = null;
        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(Program.Setting.ServerIP);
            IPEndPoint endpoint = new IPEndPoint(ip, Program.Setting.Port);
            sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                sc.Connect(endpoint);
            }
            catch
            {
                MessageBox.Show("连接服务器失败！");
                return;
            }
            MessageBox.Show("Conntected");
            UserInfo info = new UserInfo
            {
                name = "yy_computer",
                password = "123456"
            };
            string content = "Login#" + JsonConvert.SerializeObject(info);

            byte[] sendby = System.Text.Encoding.UTF8.GetBytes(content);

            sc.Send(sendby);

            reThread = new Thread(ReMsg);
            reThread.IsBackground = true;
            reThread.Start();
        }
        void ReMsg()
        {

            while (true)
            {
                byte[] merec = new byte[1024 * 1024];
                string Strmerec = System.Text.Encoding.UTF8.GetString(merec, 0, sc.Receive(merec)); //GetString方法从接受来的数组转成字符串
                Debug.WriteLine(Strmerec);
                string[] data = Regex.Split(Strmerec, "#");
                if (data[0] == "newUser")
                    continue;
                if (string.IsNullOrWhiteSpace(Strmerec))
                {
                    MessageBox.Show("连接已中断！");
                    reThread.Abort();
                    return;
                }
                JObject obj = JObject.Parse(Strmerec.Replace("Info#", ""));
                string flag = (string)obj["msg"];
                string cmd = "";

                if (flag.Length > 8)
                    if (flag.Substring(0, 8) == "DOSEARCH")
                    {
                        string[] SearchInfo = Regex.Split(flag, "_");
                        if(SearchInfo.Length>=3)
                        {
                            if(!(string.IsNullOrWhiteSpace(SearchInfo[1]) || string.IsNullOrWhiteSpace(SearchInfo[2])))
                            {
                                if(Program.SearchList.ContainsKey(SearchInfo[1]))
                                {
                                    Process.Start(Program.SearchList[SearchInfo[1]] + SearchInfo[2]);
                                }
                            }
                        }
                    }
                //if (flag == "QQ_李彤辉_你好")
                //{
                //    IntPtr hWnd = FindWindow(null, "李彤辉");
                //    if (hWnd != IntPtr.Zero)
                //    {
                //        SetForegroundWindow(hWnd);
                //        SendKeys.SendWait("你好");  //　向上键
                //        SendKeys.SendWait("{Enter}");
                //        SendKeys.SendWait("^{Enter}");
                //    }
                //}
                if (Program.Commands.Keys.Contains(flag))
                {

                    IntPtr hWnd;
                    
                    cmd = Program.Commands[flag];
                    if (cmd != "UseAPI")
                    {
                        if (flag.Contains("Close"))
                        {
                            hWnd = FindWindow(null, cmd);
                            if (hWnd != IntPtr.Zero)
                            {
                                SetForegroundWindow(hWnd);
                                SendKeys.SendWait("%{F4}");
                            }
                        }
                        else
                        {
                            if (cmd.Contains("-"))
                            {
                                string[] cmdinfo = Regex.Split(cmd, " ");
                                Process.Start(cmdinfo[0], cmdinfo[1]);
                            }
                            else
                            {
                                Process.Start(cmd);
                            }
                        }
                    }
                    else
                    {
                        if ((string)obj["msg"] == "Win_SoundOff")
                        {
                            Functions.Audio audio = new Functions.Audio();
                            audio.CloseSound();
                        }
                    }
                }
            }
        }
        class UserInfo
        {
            public string name { set; get; }
            public string password { set; get; }
            //public string ip { set; get; }
        }

        class CommandObj
        {
            public string name { set; get; }
            public string msg { set; get; }
            public string des { set; get; }
        }

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private void button2_Click(object sender, EventArgs e)
        {
            //IntPtr hWnd = FindWindow(null, "PowerPoint");
            //if (hWnd != IntPtr.Zero)
            //{
            //    SetForegroundWindow(hWnd);
            //    //SendKeys.Send("12345678");  //　向上键
            //    //SendKeys.Send("{Enter}");
            //    SendKeys.SendWait("%{F4}");
            //}
            Process.Start("shutdown");
        }

        private void Form2_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                //this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.Visible = true;
            this.notifyIcon1.Visible = false;
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            try
            {
                InitCommands.Init();
            }
            catch
            {
                MessageBox.Show("设置加载失败！");
            }
        }
    }

}
